<script lang='ts'>
import { defineComponent, h, onBeforeMount, reactive, ref, watch } from 'vue'
export default defineComponent({
	name: 'JxtechUpload'
})
</script>
<script lang='ts' setup>
import { saveUploadFileUrl } from "/@/api/org/file-attachment"
import { UploadFilled, ZoomIn, Download, Delete } from '@element-plus/icons'
import { getAccessToken } from '/@/utils/common'
import { ElNotification } from 'element-plus'
import filesServiceApi from '/@/api/org/bean/files'
const emit = defineEmits<{
	(e: 'upload-success', _response: any, _file: any, _fileList: any): void//上传成功触发事件
	(e: 'upload-error', _response: any, _file: any, _fileList: any): void//上传失败触发事件
	(e: 'upload-preview', _file: any): void//点击预览
	(e: 'upload-remove', _file: any, _fileList: any): void//移除触发事件
}>()
const jxtechUploadRef = ref()

const props = defineProps({
	// 必填
	itemType: {
		type: String,
		require: true
	},
	// 必填
	busiId: {
		type: String,
		require: true
	},
	// 必填
	compId: {
		type: String,
		require: true
	},
	// 必填
	projectid: {
		type: [String, Number],
		require: true
	},
	// 有父级时候必传
	parentid: {
		type: [String, Number],
	},
	// 是否禁用
	disabled: {
		type: Boolean,
		default: false
	},
	// 支持发送cookie凭证信息
	withCredentials: {
		type: Boolean,
		default: false
	},
	// 支持上传文件类型 （thumbnail-mode 模式下此参数无效）
	accept: {
		type: String,
		default: 'txt,png,ppt,pptx,doc,docx,war,zip,bmp,gif,jpg,jpeg,xls,xlsx,pdf,mov,mp4,json,tif,dwg'
	},
	// 是否显示缩略图 
	thumbnailMode: {
		type: Boolean,
		default: false
	},
	// 最大上传数量 (files, fileList)
	limit: {
		type: Number,
		default: 10
	},
})

const uploadState = reactive({
	jxtechUploadShow: ref(true),
	headers: { Authorization: '' },
	// imgUrl: '',
	multiple: true,
	fileList: [] as any,
	srcList: [] as any,
	//上传附带的参数
	data: {
		itemType: props.itemType,
		busiId: props.busiId,
		compId: props.compId,
		projectid: props.projectid,
		typeid: props.parentid
	},
	// 进度条
	percentage: 0,
	progresColor: '#689bfb',
	onPreview: (_file: any) => {
		// 点击预览
		emit("upload-preview", _file)
	},
	onRemove: (_file: any, _fileList: any) => {
		ElNotification({
			title: '文件移除',
			message: _file.name,
			type: 'success',
			duration: 0
		})
		emit("upload-remove", _file, _fileList)
	},
	onSuccess: (_response: any, _file: any, _fileList: any) => {
		console.log(_fileList)
		uploadState.progresColor = "#7eb87e"
		console.log(_response)
		ElNotification({
			title: '上传成功',
			message: _file.name,
			type: 'success',
		})
		emit("upload-success", _response, _file, _fileList)
	},
	onError: (_response: any, _file: any, _fileList: any) => {
		console.log("上传on error", _file)
		uploadState.progresColor = "red"
		ElNotification({
			title: '上传失败',
			message: _file.name,
			type: 'error',
			duration: 0
		})
		emit("upload-error", _response, _file, _fileList)
	},
	onProgress: (event: any, file: any, fileList: any) => {
		uploadState.percentage = event.percent
	},
	// 文件上传超过限制
	onExceed: () => {
		ElNotification({
			message: h('span', { style: 'color: red' }, '待上传文件数量超过限制！'),
		})
	},
	// ---方法---
	//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用 (file, fileList)
	onChange: (file: any, fileList: any) => {
		uploadState.fileList = fileList
	},
	// 清除已经上传的文件列表 （该方法不支持在 before-upload 中调用）
	clearFiles: () => {
		jxtechUploadRef.value.clearFiles()
	},
	// 取消上传请求
	abort: () => {
		jxtechUploadRef.value.abort()
	},
	//手动上传文件列表
	submit: () => {
		jxtechUploadRef.value.submit()
	},
	// 取消按钮
	// uploadBtnCancel: () => {
	// 	uploadDialogVisible.value = false
	// },
	// 上传按钮
	uploadBtnOk: () => {
		jxtechUploadRef.value.submit()
	}
})
const uploadItemHandle = reactive({
	// 点击预览
	pictureCardPreview: (file: any) => {
		console.log("预览")
		console.log(uploadState.srcList)
	},
	// 点击下载
	filesDownload: (file: any) => {

	},
	// 点击删除
	filesRemove: (file: any) => {
		console.log(file)

		if (file.status === "ready") {
			let newList: { uid: any }[] = []
			uploadState.fileList.forEach((item: { uid: any }) => {
				if (item.uid !== file.uid) {
					newList.push(item)
				}
			})
			uploadState.fileList = newList
		} else if (file.status === "success") {
			// 上传成功后点击删除 待续
			let bean = { uuid: '', ftype: '' }
			filesServiceApi.delFiles([bean])

		}
	},
	iconName: (file: any) => {
		const t = file.name.split('.')
		const fileType = t[t.length - 1]
		switch (fileType) {
			case 'txt':
				return "#icon-txt"
			case 'xlsx':
				return "#icon-Excel"
			case 'xls':
				return "#icon-Excel"
			case 'docx':
				return "#icon-Word"
			case 'doc':
				return "#icon-Word"
			case 'PPTX':
				return "#icon-PPT"
			case 'PDF':
				return "#icon-Pdf"
			case 'Mp4':
				return "#icon-shipin"
			case 'wps':
				return "#icon-WPS"
			default:
				return "#icon-weizhiwenjian"
		}
	}

})
watch(() => uploadState.fileList.length, () => {
	let srcList: any[] = []
	if (uploadState.fileList.length > 0) {
		uploadState.fileList.forEach((item: { raw: { type: string }; url: any }) => {
			if (item.raw.type === "image/png")
				srcList.push(item.url)
		})
	}
	uploadState.srcList = srcList
})
onBeforeMount(() => {
	if (!props.itemType || !props.busiId || !props.compId || !props.projectid) {
		uploadState.jxtechUploadShow = false
		ElNotification({
			title: '注意：上传组件缺少必要参数',
			message: h('span', { style: 'color: red' }, 'itemType || busiId || compId || projectid'),
			duration: 0,
		})
	}
	// 限制为单文件上传的时候 禁止文件多选
	props.limit == 1 ? uploadState.multiple = false : true
	//写入token
	let token = getAccessToken()
	uploadState.headers['Authorization'] = "bearer " + token
})


</script>
<template>
	<div v-if="uploadState.jxtechUploadShow">
		<div class="jxtech-upload-container">
			<el-upload
				:action="saveUploadFileUrl"
				method="POST"
				ref="jxtechUploadRef"
				class="upload-box"
				name="files"
				list-type="picture"
				:auto-upload="false"
				:drag="true"
				:show-file-list="true"
				:multiple="uploadState.multiple"
				:limit="props.limit"
				:accept="props.accept"
				:disabled="props.disabled"
				:thumbnail-mode="props.thumbnailMode"
				:with-credentials="props.withCredentials"
				:headers="uploadState.headers"
				:data="uploadState.data"
				:file-list="uploadState.fileList"
				:on-preview="uploadState.onPreview"
				:on-remove="uploadState.onRemove"
				:on-success="uploadState.onSuccess"
				:on-error="uploadState.onError"
				:on-progress="uploadState.onProgress"
				:on-change="uploadState.onChange"
				:on-exceed="uploadState.onExceed"
			>
				<template #file="{ file }">
					<div class="upload-list__item">
						<div class="upload-list__item-pre">
							<div class="upload-list__item-thumbnail-box">
								<img
									v-if="file.raw.type == 'image/jpg' || file.raw.type == 'image/png' || file.raw.type == 'image/jpeg'"
									:src="file.url"
									class="upload-list__item-thumbnail"
								/>
								<jxtech-svg-icon v-else :size="66" :icon="uploadItemHandle.iconName(file)"></jxtech-svg-icon>
							</div>
							<span class="upload-list__item-actions">
								<span
									v-if="file.raw.type == 'image/png' || file.raw.type == 'image/jpeg'"
									class="upload-list__item-preview"
									@click="uploadItemHandle.pictureCardPreview(file)"
								>
									<el-icon>
										<zoom-in />
									</el-icon>
								</span>
								<!-- <span
									v-if="!disabled"
									class="upload-list__item-delete"
									@click="uploadItemHandle.filesDownload(file)"
								>
									<el-icon>
										<download />
									</el-icon>
								</span>-->
								<span
									v-if="!disabled"
									class="upload-list__item-delete"
									@click="uploadItemHandle.filesRemove(file)"
								>
									<el-icon>
										<delete />
									</el-icon>
								</span>
							</span>
						</div>
						<div class="upload-list__item-detail">
							<h5>{{ file.name }}</h5>
							<h5></h5>
							<el-progress :percentage="file.percentage" :color="uploadState.progresColor" />
						</div>
					</div>
				</template>

				<el-icon class="el-icon--upload">
					<upload-filled />
				</el-icon>
				<div class="el-upload__text">
					拖拽或
					<em>点击添加文件</em>
				</div>
			</el-upload>
		</div>
		<div class="jxtech-upload-footer">
			<!-- txt,png,ppt,pptx,doc,docx,war,zip,bmp,gif,jpg,jpeg,xls,xlsx,pdf,mov,mp4,json,tif,dwg -->
			<div style="color: red">*可以上传{{ props.accept }}格式，任意大小的文件</div>
			<div>
				<!-- <jxtech-cancel-button @click="uploadState.uploadBtnCancel"></jxtech-cancel-button> -->
				<jxtech-upload-button @click="uploadState.uploadBtnOk"></jxtech-upload-button>
			</div>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.jxtech-upload-box {
	height: 100%;
}
.jxtech-upload-container {
	width: 100%;
	border: 1px solid #ccc;
	border-radius: 6px;
	.upload-box {
		width: 100%;
		height: 400px;
		padding: 10px;
		display: flex;
		justify-content: space-between;
	}
	::v-deep(.el-upload) {
		width: 50%;
		margin-right: 20px;
	}
	::v-deep(.el-upload-dragger) {
		height: 380px;
		// width: 400px;
		width: 100%;
		margin-right: 20px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
}
::v-deep(.el-upload-list) {
	width: 600px;
	overflow: auto;
}
.jxtech-upload-footer {
	height: 60px;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

::v-deep(.el-icon--document) {
	display: none;
}
::v-deep(.el-upload-list__item) {
	padding: 10px;
}
.upload-list__item {
	display: flex;
	// justify-content: space-between;
	// align-items: center;

	&-pre {
		// width: 60px;
		height: 70px;
		width: 100px;
		position: relative;
	}
	&-thumbnail-box {
		text-align: center;
		width: 100px;
		height: 70px;
		line-height: 70px;
	}
	&-thumbnail {
		width: 100px;
		height: 70px;
	}

	&-actions {
		position: absolute;
		top: 0;
		width: 100px;
		height: 70px;
		display: none;
		background-color: rgba(0, 0, 0, 0.4);
		span {
			color: white;
			cursor: pointer;
		}
	}
	.upload-list__item-detail {
		padding: 10px;
		width: 390px;
		height: 70px;
		h5 {
			padding-bottom: 10px;
		}
	}
}
.upload-list__item:hover {
	.upload-list__item-actions {
		// background-color: #fff;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
}
::v-deep(.el-progress__text) {
	top: -30px;
}
</style>
